<?php
/**
 * Created by 惠达浪
 * Email: crazys@126.com
 * Date: 2018/11/21
 * Time: 13:15
 */

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\facade\MesLogic;
use app\api\facade\TokenService;
use app\api\facade\UserLogic;
use app\api\validate\UserValidate;
use app\lib\enum\ErrorCodeEnum;
use app\lib\enum\MesEnum;
use app\lib\exception\DenyException;

class User extends BaseController {
    protected $beforeActionList = [
        'checkToken' => ['except' => 'postLogin,postMobileLogin'],
    ];

    /**
     * 获取用户信息
     *
     * @return \think\response
     */
    public function getUserInfo() {
        $userInfo = UserLogic::getUserInfoByToken($this->token);
        return $this->returnData($userInfo);
    }

    /**
     * 用户登录
     * 成功返回token，失败返回原因
     *
     * @throws \app\lib\exception\ParameterException
     */
    public function postLogin() {
        (new UserValidate())->scene('login')->goCheck();
        $post = $this->request->post();

        // $result 登录成功时为token字符串，失败时为状态码
        $result = UserLogic::login($post['username'], $post['password'], $post['device_no']);

        if (isset($result['token'])) {
            $header = [
                'Authorization' => 'Bearer ' . $result['token'],
                'Cache-Control' => 'no-store'
            ];
            $this->success('登录成功', $result, $header);
        }
        $this->error($result['msg'], $result['errCode'], [], [], 401);
    }

    /**
     * 手机用户登录
     * 成功返回用户数据，失败返回错误
     *
     * @throws \app\lib\exception\ParameterException
     */
    public function postMobileLogin() {
        (new UserValidate())->scene('mobile_login')->goCheck();
        $postData = $this->request->post();
        $user = UserLogic::mobileLogin($postData['username'], $postData['password']);

        if ($user === false) {
            $this->error('登录失败', ErrorCodeEnum::LOGIN_FALLED, [], [], 401);
        }

        $header = [
            'Authorization' => 'Bearer ' . $user['token'],
            'Cache-Control' => 'no-store'
        ];
        $this->success('登录成功', $user, $header);
    }

    /**
     * 上班
     *
     * @throws DenyException
     * @throws \app\lib\exception\ParameterException
     */
    public function postWorkStart() {
        $this->processWork('on');
    }

    /**
     * 下班
     *
     * @throws DenyException
     * @throws \app\lib\exception\ParameterException
     */
    public function postWorkEnd() {
        $this->processWork('off');
    }

    /**
     * 上下班逻辑
     * 由于上下班逻辑极其相似，因此统一处理
     *
     * @param string $action on上班，off下班
     *
     * @return void 成功返回用户信息，失败返回错误信息数组
     * @throws DenyException
     * @throws \app\lib\exception\ParameterException
     */
    private function processWork($action = '') {
        (new UserValidate())->scene('work')->goCheck();

        //判断任务状态，任务处理开始或完成状态，不能上下班
        $rid = $this->request->post('result_id/d');
        $taskStatus = MesLogic::getResultStatus($rid);
        if ($taskStatus == MesEnum::RESULT_START) {
            throw new DenyException('任务已经开始', ErrorCodeEnum::TASK_ALREADY_START);
        }

        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $workcenterid = TokenService::getWorkcenterIdByToken($this->token);

        //判断上下班操作
        if ($action == 'on') {
            $msg = '上班';
            $user = UserLogic::workStart($username, $password, $workcenterid);
        } else {
            $msg = '下班';
            $user = UserLogic::workEnd($username, $password, $workcenterid);
        }
        if ($user instanceof \app\api\model\User) {
            $this->success($msg . '操作成功', ['user' => $user]);
        }
        $this->error($user['msg'], $user['errCode'], null, [], 401);
    }

}
